package com.pps.fragment;

import java.io.File;
import java.io.InputStream;
import java.util.List;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.pps.activity.R;
import com.pps.adapter.MyListAdapter;
import com.pps.adapter.MyListGridAdapter;
import com.pps.adapter.MyPopupWinAdapter;
import com.pps.commom.MemoryStatus;
import com.pps.custom.anim.MyAnimation;
import com.pps.model.SubModel;
import com.pps.utils.DownXML;
import com.pps.utils.JudgeNetwork;
import com.pps.utils.ZipToFile;
import com.pps.xmlparser.ListXMLContentHandler;

/**
 * 影视列表的界面
 * 
 * @author jiangqq
 * 
 */
public class MyListFragment extends Fragment {
	private ImageButton btn_ic_title_menu;
	private Button btn_top_grid_list;
	private Button btn_bkg_poster_cover;
	private Button btn_list_hot;
	private Button btn_list_new;
	private Button btn_list_score;
	private Button btn_list_letter;
	private LinearLayout list_grid_linear;
	private ListView lv_list;
	private GridView gv_list;
	private static List<SubModel> mLists; // 静态节目列表数据
	private MyListAdapter listAdapter;
	private MyListGridAdapter gridAdapter;
	public static ProgressDialog mProgressDialog;
	private View mView;
	private Context mContext;
	private boolean isClick = false;// 控制表格与列表切换按钮
									// 默认isClick=false(列表)，isClick=true(表格)

	// PopupWindow弹出框进行显示所需要的各种参数
	private PopupWindow mPopupWindow;
	private MyPopupWinAdapter myPopupWinAdapter;
	private ListView lv_popwindow;
	private TextView tv_popupwindow_type;
	private TextView tv_popupwindow_year;
	private TextView tv_popupwindow_letter;
	private View mPopupWindowView;
	private LayoutInflater mLayoutInflater;
	private String[] mStrs;// 显示类型，年份，字母的数组

	private static final String TAG = "MyListFragment";
	private Handler mHandler = new Handler() {
		@SuppressWarnings("unchecked")
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 0:
				break;
			case 1:
				if (mProgressDialog != null) {
					mProgressDialog.dismiss();
				}
				mLists = (List<SubModel>) msg.obj;
				// System.out.println(mLists.toString());
				Log.i(TAG, "节目列表的Item数量:" + mLists.size());
				listAdapter = new MyListAdapter(mLists, mContext, getActivity());
				lv_list.setAdapter(listAdapter);
				break;
			}
			super.handleMessage(msg);
		}
	};

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		if (mView == null) {

			mView = inflater.inflate(R.layout.fragment_list, container, false);

			initView();
			initVariable();
			mProgressDialog = new ProgressDialog(mContext);
			mProgressDialog.setMessage("正在加载...");
			mProgressDialog.setCancelable(false);
			mProgressDialog.show();
			Thread thread = new Thread(runnable_id);
			thread.start();
			bindData();
			initListeners();
		}
		return mView;
	}

	private void initVariable() {
		mContext = mView.getContext();

		// 进行筛选，弹出PopupWindow
		mLayoutInflater = LayoutInflater.from(mContext);
		mPopupWindowView = mLayoutInflater.inflate(
				R.layout.fragment_list_popupwindow, null);
		mPopupWindowView.setFocusable(true);
		mPopupWindowView.setFocusableInTouchMode(true);
		// 监听返回键,进行dismiss()掉popupwindow
		mPopupWindowView.setOnKeyListener(new OnKeyListener() {
			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				if (event.getAction() == KeyEvent.ACTION_DOWN
						&& keyCode == KeyEvent.KEYCODE_BACK) {
					if (mPopupWindow.isShowing()) {
						mPopupWindow.dismiss();
					}
				}
				return false;
			}
		});
		// 获取该加载出来view中的控件;
		lv_popwindow = (ListView) mPopupWindowView
				.findViewById(R.id.lv_popwindow);
		tv_popupwindow_type = (TextView) mPopupWindowView
				.findViewById(R.id.tv_popupwindow_type);
		tv_popupwindow_year = (TextView) mPopupWindowView
				.findViewById(R.id.tv_popupwindow_year);
		tv_popupwindow_letter = (TextView) mPopupWindowView
				.findViewById(R.id.tv_popupwindow_letter);
		mStrs = getResources().getStringArray(R.array.array_type_item);
	}

	private void initView() {
		btn_ic_title_menu = (ImageButton) mView
				.findViewById(R.id.btn_ic_title_menu);
		btn_ic_title_menu.setBackgroundResource(0);// 去掉背景
		btn_top_grid_list = (Button) mView.findViewById(R.id.btn_top_grid_list);
		// btn_top_grid_list.setBackgroundResource(0);//去掉背景
		btn_bkg_poster_cover = (Button) mView
				.findViewById(R.id.btn_bkg_poster_cover);
		btn_list_hot = (Button) mView.findViewById(R.id.btn_list_hot);
		btn_list_new = (Button) mView.findViewById(R.id.btn_list_new);
		btn_list_score = (Button) mView.findViewById(R.id.btn_list_score);
		btn_list_letter = (Button) mView.findViewById(R.id.btn_list_letter);
		lv_list = (ListView) mView.findViewById(R.id.lv_list);
		gv_list = (GridView) mView.findViewById(R.id.gv_list);
		list_grid_linear = (LinearLayout) mView
				.findViewById(R.id.list_grid_linear);

	}

	private void bindData() {
	}

	/**
	 * 初始化，进行监听
	 */
	private void initListeners() {
		btn_ic_title_menu.setOnClickListener(new MySetOnClickListener());
		btn_top_grid_list.setOnClickListener(new MySetOnClickListener());
		btn_bkg_poster_cover.setOnClickListener(new MySetOnClickListener());
		btn_list_hot.setOnClickListener(new MySetOnClickListener());
		btn_list_new.setOnClickListener(new MySetOnClickListener());
		btn_list_score.setOnClickListener(new MySetOnClickListener());
		btn_list_letter.setOnClickListener(new MySetOnClickListener());
		lv_list.setOnItemClickListener(new MyOnItemClickListener());
		gv_list.setOnItemClickListener(new MyOnItemClickListener());

		tv_popupwindow_type.setOnClickListener(new MySetOnClickListener());
		tv_popupwindow_year.setOnClickListener(new MySetOnClickListener());
		tv_popupwindow_letter.setOnClickListener(new MySetOnClickListener());

	}

	/*
	 * 自定义按钮点击事件
	 */
	class MySetOnClickListener implements OnClickListener {
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.btn_ic_title_menu:
				break;
			case R.id.btn_top_grid_list:
				// 进行节目的表格与列表的切换
				if (!isClick) {
					// 切换成表格,并且设置标志为true
					lv_list.setVisibility(View.GONE);
					gridAdapter = new MyListGridAdapter(mLists, mContext,
							getActivity());
					gv_list.setAdapter(gridAdapter);
					btn_top_grid_list
							.setBackgroundResource(R.drawable.icon_top_list);
					gv_list.setVisibility(View.VISIBLE);
					list_grid_linear.setAnimation(new MyAnimation());
					isClick = true;
				} else {
					// 切换成列表,并且设置标志位false
					lv_list.setVisibility(View.VISIBLE);
					listAdapter = new MyListAdapter(mLists, mContext,
							getActivity());
					lv_list.setAdapter(listAdapter);
					btn_top_grid_list
							.setBackgroundResource(R.drawable.icon_top_grid);
					gv_list.setVisibility(View.GONE);
					list_grid_linear.setAnimation(new MyAnimation());
					isClick = false;
				}

				break;
			case R.id.btn_bkg_poster_cover:
				// listview进行绑定数据
				myPopupWinAdapter = new MyPopupWinAdapter(mContext, mStrs);
				lv_popwindow.setAdapter(myPopupWinAdapter);
				mPopupWindow = new PopupWindow(mPopupWindowView,
						LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,
						true);
				mPopupWindow.setFocusable(true);
				mPopupWindow.setTouchable(true);
				mPopupWindow.setOutsideTouchable(true);
				// 点击让Popupwindowd点击外面可以消失掉
				mPopupWindow.setBackgroundDrawable(new ColorDrawable(0));

				if (!mPopupWindow.isShowing()) {
					// 显示进行PopupWindow
					mPopupWindow.showAsDropDown(btn_bkg_poster_cover, 0, 0);
				} else {
					mPopupWindow.dismiss();
				}
				break;
			case R.id.btn_list_hot:
				btn_list_hot.setBackgroundResource(R.drawable.tab_bar_sel);
				btn_list_new.setBackgroundResource(R.drawable.tab_bar);
				btn_list_score.setBackgroundResource(R.drawable.tab_bar);
				btn_list_letter.setBackgroundResource(R.drawable.tab_bar);
				break;
			case R.id.btn_list_new:
				btn_list_hot.setBackgroundResource(R.drawable.tab_bar);
				btn_list_new.setBackgroundResource(R.drawable.tab_bar_sel);
				btn_list_score.setBackgroundResource(R.drawable.tab_bar);
				btn_list_letter.setBackgroundResource(R.drawable.tab_bar);
				break;
			case R.id.btn_list_score:
				btn_list_hot.setBackgroundResource(R.drawable.tab_bar);
				btn_list_new.setBackgroundResource(R.drawable.tab_bar);
				btn_list_score.setBackgroundResource(R.drawable.tab_bar_sel);
				btn_list_letter.setBackgroundResource(R.drawable.tab_bar);
				break;
			case R.id.btn_list_letter:
				btn_list_hot.setBackgroundResource(R.drawable.tab_bar);
				btn_list_new.setBackgroundResource(R.drawable.tab_bar);
				btn_list_score.setBackgroundResource(R.drawable.tab_bar);
				btn_list_letter.setBackgroundResource(R.drawable.tab_bar_sel);
				break;

			case R.id.tv_popupwindow_type:
				// 根据类型显示筛选视频
				mStrs = getResources().getStringArray(R.array.array_type_item);
				myPopupWinAdapter = new MyPopupWinAdapter(mContext, mStrs);
				lv_popwindow.setAdapter(myPopupWinAdapter);
				break;
			case R.id.tv_popupwindow_year:
				// 根据年份显示筛选视频
				mStrs = getResources().getStringArray(R.array.array_year_item);
				myPopupWinAdapter = new MyPopupWinAdapter(mContext, mStrs);
				lv_popwindow.setAdapter(myPopupWinAdapter);
				break;
			case R.id.tv_popupwindow_letter:
				// 根据字母显示筛选视频
				mStrs = getResources()
						.getStringArray(R.array.array_letter_item);
				myPopupWinAdapter = new MyPopupWinAdapter(mContext, mStrs);
				lv_popwindow.setAdapter(myPopupWinAdapter);
				break;
			}
		}
	}

	/*
	 * 自定义列表点击事件
	 */
	class MyOnItemClickListener implements OnItemClickListener {
		@Override
		public void onItemClick(AdapterView<?> parent, View view,
				final int position, long id) {
			// 点击列表Item进入详情页面
			// .......
			FragmentManager fragmentManager = getFragmentManager();
			FragmentTransaction transaction = fragmentManager
					.beginTransaction();
			MyDetailFragment detailFragment = new MyDetailFragment();
			Bundle bundle = new Bundle();
			bundle.putInt("sub_id", mLists.get(position).getId());
			detailFragment.setArguments(bundle);
			transaction.replace(R.id.container_details, detailFragment);
			transaction.addToBackStack(null);
			transaction.commit();
		}
	}

	/**
	 * 后台线程请求数据，并且进行数据的XML解析
	 */
	Runnable runnable_id = new Runnable() {
		@Override
		public void run() {
			try {
				if (JudgeNetwork.isNetworkConnected(mContext)) {
					// 如果内存中有数据，那就直接进行显示
					if (mLists != null && mLists.size() >= 0) {
						mHandler.obtainMessage(1, mLists).sendToTarget();
					} else {
						// 内存中没有数据，进行下载解析
						// a:首先进行判断是否sdcard中存在节目列表的xml文件
						// b:如果存在直接进行解析，然后把数据放入到内存当中<->如果不存在那么去网络中进行下载节目列表zip包，进行解压缩，然后在放入到内存当中
						if (MemoryStatus.externalMemoryAvailable()) {
							File file = new File("/sdcard/141.xml/141.xml");
							if (file.exists()) {
								// 文件存在进行XML解析
								InputStream inputStream = DownXML
										.getXMLFromFile(file);
								SAXParserFactory spf = SAXParserFactory
										.newInstance();
								SAXParser parser = spf.newSAXParser();
								ListXMLContentHandler handler = new ListXMLContentHandler();
								parser.parse(inputStream, handler);
								inputStream.close();
								mLists = handler.getmLists();
								mHandler.obtainMessage(1, mLists)
										.sendToTarget();
							} else {
								// 文件不存在-去网上上面进行下载zip包，然后解压缩，解析数据
								// 1，去网络上面请求数据
								DownXML.getFile("http://list1.ppstream.com/mobile/newipadc/sub/141.xml.zip");
								// 2,对压缩包进行解压缩
								boolean flag = ZipToFile.unzip("/sdcard",
										"141.xml.zip", "/sdcard/141.xml");
								if (flag) {
									Log.i(TAG, "解压成功.....");
									// 解压成功，并且删除该压缩包,
									File file_zip = new File(
											"/sdcard/141.xml.zip");
									if (file_zip.exists()) {
										file_zip.delete();
									}
								} else {
									Log.i(TAG, "解压失败.....");
								}
								// 3，对获取到的XML数据进行解析
								// InputStream
								// inputStream=MyListActivity.class.getClassLoader().getResourceAsStream("141.xml");
								InputStream inputStream = DownXML
										.getXMLFromFile(new File(
												"/sdcard/141.xml/141.xml"));
								SAXParserFactory spf = SAXParserFactory
										.newInstance();
								SAXParser parser = spf.newSAXParser();
								ListXMLContentHandler handler = new ListXMLContentHandler();
								parser.parse(inputStream, handler);
								inputStream.close();
								mLists = handler.getmLists();
								mHandler.obtainMessage(1, mLists)
										.sendToTarget();
							}
						}
					}

					// // 1，去网络上面请求数据
					// DownXML.getFile("http://list1.ppstream.com/mobile/newipadc/sub/141.xml.zip");
					// // 2,对压缩包进行解压缩
					// boolean flag = ZipToFile.unzip("/sdcard", "141.xml.zip",
					// "/sdcard/141.xml");
					// if (flag) {
					// Log.i(TAG, "解压成功.....");
					// // 解压成功，并且删除该压缩包,
					// File file = new File("/sdcard/141.xml.zip");
					// if (file.exists()) {
					// file.delete();
					// }
					// } else {
					// Log.i(TAG, "解压失败.....");
					// }
					// // 3，对获取到的XML数据进行解析
					// // InputStream
					// //
					// inputStream=MyListActivity.class.getClassLoader().getResourceAsStream("141.xml");
					// InputStream inputStream = DownXML.getXMLFromFile(new
					// File(
					// "/sdcard/141.xml/141.xml"));
					// SAXParserFactory spf = SAXParserFactory.newInstance();
					// SAXParser parser = spf.newSAXParser();
					// ListXMLContentHandler handler = new
					// ListXMLContentHandler();
					// parser.parse(inputStream, handler);
					// inputStream.close();
					// mLists = handler.getmLists();
					// mHandler.obtainMessage(1, mLists).sendToTarget();
					// // XML文件解析完成，删除该xml文件以及上层空文件夹
					// //FileUtils.deleteAll(new
					// File("/sdcard/141.xml"));-->已经转移到使用广播进行删除

				} else {
					// 没有网络连接
					Toast.makeText(mContext, "当前没有网络连接，使用缓存资源。",
							Toast.LENGTH_SHORT).show();
					File file = new File("/sdcard/141.xml/141.xml");
					if (file.exists()) {
						// 文件存在进行XML解析
						InputStream inputStream = DownXML.getXMLFromFile(file);
						SAXParserFactory spf = SAXParserFactory.newInstance();
						SAXParser parser = spf.newSAXParser();
						ListXMLContentHandler handler = new ListXMLContentHandler();
						parser.parse(inputStream, handler);
						inputStream.close();
						mLists = handler.getmLists();
						mHandler.obtainMessage(1, mLists).sendToTarget();
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	};
}
